package com.yilin.tms.gps.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.yilin.commons.encrypt.SM2WithSM3Utils;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.tms.core.entity.gps.Location;
import com.yilin.tms.core.entity.gps.hyb.DeviceTrack;
import com.yilin.tms.core.entity.gps.VehicleGps;
import com.yilin.tms.core.entity.order.goods.GoodsOrder;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.truck.TruckVehicle;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.gps.service._IGpsHybService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author liuxu :)
 * @version 1.0
 * @date 2022-11-1 0001
 */
@Service
@Transactional
public class _GpsHybService implements _IGpsHybService {

    private Integer sdkStatus = 1;//交通SDK自动上报: 1 开启 0 关闭，默认关闭
    private Integer notifyStatus = 1;//触发推送: 1 开启 0 关闭，默认开启
    //企业id
    private String aGENT_ID = "Gzylwl";
    //私钥
    private String privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgLXuhPfZGASeiKHLOVGJ1Me0vuzRlR2Kaq/P2w3gK+3WgCgYIKoEcz1UBgi2hRANCAAThn0gkCu7/vBOECk3CKbw9VLxRuysYHKEuSRQRSYT8nP/D2fm84FRHhGU/1Fzx4iddnNroRzQUxwz+p7NriUQy";
    //配置围栏（业务传入运单）
    private String ConfigureUrl = "https://agent.haoyunbao56.com/shipping_fence/store";//配置围栏（业务传入运单）
    private String stopUrl = "https://agent.haoyunbao56.com/shipping_fence/delete"; //终止围栏
    private String getTackUrl = "https://agent.haoyunbao56.com/device_track/get_track_by_shipping";   //获取轨迹（通过运单号）
    private String activeDeviceListUrl = "https://agent.haoyunbao56.com/device_track/active_list";//获取活跃设备列表
    private String getTreasureInfoUrl = "https://agent.haoyunbao56.com/shipping_fence/pull";//获取围栏详情
    private String getActiveInfoUrl = "https://agent.haoyunbao56.com/device_track/fetch_device_info";//获取设备信息（通过设备号）
    private String getTransitListUrl = "https://agent.haoyunbao56.com/shipping_fence/shipping_list";  //获取运单列表
    private String testUrl = "https://agent.haoyunbao56.com/device_task/fake_report";//测试
    private boolean enclosure = false;

    @Override
    public String configureTreasure(Account truckUser, TruckVehicle truckVehicle, GoodsOrder goodsBasic, TransitOrder transitBasic) {
        return null;
    }

    @Override
    public String stopTreasure(String transportNo) {
        return null;
    }

    //获取轨迹（通过运单号）
    @Override
    public List<Location> getTack(String transportNo, String vehicleNo, Date startTime, Date endTime) {
        if (startTime == null) return null;
        //从好运宝获取gps
        if (transportNo == null) throw new BusinessException("运单号不能为空！");
        Map<String, Object> map = new HashMap<>();
        map.put("shippingNoteNumber", transportNo);
        map.put("serialNumber", "0001");
        //请求
        Gson gson = new Gson();
        String json = gson.toJson(map);
        String signedData = SM2WithSM3Utils.sign(privateKey, json);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response;
        String resultString = "";
        HttpPost httpPost;
        try {
            httpPost = new HttpPost(getTackUrl);
            httpPost.addHeader("X-AGENT-ID", aGENT_ID);
            httpPost.addHeader("X-SIGNATURE", signedData);
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            HashMap hashMap = JSON.parseObject(resultString, HashMap.class);
            //获取好运宝数据
            List<Location> locationList = new ArrayList<>();
            long stopTime = 0;
            List<Long> listTime = new ArrayList<>();
            if (hashMap.get("message").equals("SUCCESS")) {
                if (!hashMap.get("body").equals("null") && hashMap.get("body") != null) {
                    List<DeviceTrack> deviceTrackList = (List<DeviceTrack>) hashMap.get("body");
                    for (int i = 0; i < deviceTrackList.size(); i++) {
                        DeviceTrack deviceTrack = JSON.parseObject(String.valueOf(deviceTrackList.get(i)), DeviceTrack.class);
                        deviceTrack.setLat(deviceTrack.getLat());
                        deviceTrack.setLng(deviceTrack.getLng());
                        Location location = new Location();
                        location.setmBearing(deviceTrack.getDirection() == null ? 0 : deviceTrack.getDirection());
                        location.setmLatitude(deviceTrack.getLat());
                        location.setmLongitude(deviceTrack.getLng());
                        location.setmSpeed(deviceTrack.getSpeed() == null ? 0 : deviceTrack.getSpeed());
                        long longTime = deviceTrack.getLocateTime() * (long) 1000;
                        location.setmTime(DateTimeUtil.stringToDate(DateTimeUtil.longDateString(longTime), null));
                        location.setStopTimeTip("0");
                        if (i == 0) {
                            if (location.getmSpeed() == 0) location.setStop(true);
                            locationList.add(location);
                        } else if (location.getmSpeed() != 0) {
                            DeviceTrack deviceTrackS = JSON.parseObject(String.valueOf(deviceTrackList.get(i - 1)), DeviceTrack.class);
                            deviceTrackS.setLat(deviceTrackS.getLat());
                            deviceTrackS.setLng(deviceTrackS.getLng());
                            if (listTime.size() > 0) {
                                Location locations = new Location();
                                locations.setmSpeed(0);
                                locations.setmLatitude(deviceTrackS.getLat());
                                locations.setmLongitude(deviceTrackS.getLng());
                                locations.setmBearing(deviceTrackS.getDirection());
                                locations.setStop(true);
                                if (listTime.size() >= 2) {
                                    stopTime = listTime.get(listTime.size() - 1) - listTime.get(0);
                                    locations.setStopTimeTip(Long.toString(stopTime / 1000 / 60));
                                } else if (listTime.size() == 1) {
                                    stopTime = location.getmTime().getTime() - listTime.get(0);
                                    locations.setStopTimeTip(Long.toString((stopTime / 1000) / 60));
                                }
                                locationList.add(locations);
                                listTime = new ArrayList<>();
                            }
                            locationList.add(location);
                        } else if (i == deviceTrackList.size() - 1) {
                            location.setStop(true);
                            if (listTime.size() >= 2) {
                                stopTime = listTime.get(listTime.size() - 1) - listTime.get(0);
                                location.setStopTimeTip(Long.toString(stopTime / 1000 / 60));
                            } else if (listTime.size() == 1) {
                                stopTime = location.getmTime().getTime() - listTime.get(0);
                                location.setStopTimeTip(Long.toString((stopTime / 1000) / 60));
                            } else {
                                location.setStopTimeTip("0");
                            }
                            locationList.add(location);
                        } else {
                            listTime.add(location.getmTime().getTime());
                        }
                    }
                    //保存缓存数据
                    return locationList;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String activeDeviceList() {
        return null;
    }

    @Override
    public VehicleGps getActiveInfo(String device, String vehicleNumber) {
        return null;
    }

    @Override
    public String getTreasureInfo(String transportNo) {
        return null;
    }

    //获取运单列表
    @Override
    public String getTransitList(String transportNo) {
        if (transportNo == null) throw new BusinessException("运单号不能为空！");
        Map<String, Object> map = new HashMap<>();
        map.put("device", transportNo);
        map.put("vehicleNumber", "0001");
        map.put("startTime", "0001");
        map.put("endTime", "0001");
        //请求
        Gson gson = new Gson();
        String json = gson.toJson(map);
        String signedData = SM2WithSM3Utils.sign(privateKey, json);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response;
        String resultString = "";
        HttpPost httpPost;
        try {
            httpPost = new HttpPost(getTransitListUrl);
            httpPost.addHeader("X-AGENT-ID", aGENT_ID);
            httpPost.addHeader("X-SIGNATURE", signedData);
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultString;
    }

    public Integer getSdkStatus() {
        return sdkStatus;
    }

    public void setSdkStatus(Integer sdkStatus) {
        this.sdkStatus = sdkStatus;
    }

    public Integer getNotifyStatus() {
        return notifyStatus;
    }

    public void setNotifyStatus(Integer notifyStatus) {
        this.notifyStatus = notifyStatus;
    }

    public String getaGENT_ID() {
        return aGENT_ID;
    }

    public void setaGENT_ID(String aGENT_ID) {
        this.aGENT_ID = aGENT_ID;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }

    public String getConfigureUrl() {
        return ConfigureUrl;
    }

    public void setConfigureUrl(String configureUrl) {
        ConfigureUrl = configureUrl;
    }

    public String getStopUrl() {
        return stopUrl;
    }

    public void setStopUrl(String stopUrl) {
        this.stopUrl = stopUrl;
    }

    public String getGetTackUrl() {
        return getTackUrl;
    }

    public void setGetTackUrl(String getTackUrl) {
        this.getTackUrl = getTackUrl;
    }

    public String getActiveDeviceListUrl() {
        return activeDeviceListUrl;
    }

    public void setActiveDeviceListUrl(String activeDeviceListUrl) {
        this.activeDeviceListUrl = activeDeviceListUrl;
    }

    public String getGetTreasureInfoUrl() {
        return getTreasureInfoUrl;
    }

    public void setGetTreasureInfoUrl(String getTreasureInfoUrl) {
        this.getTreasureInfoUrl = getTreasureInfoUrl;
    }

    public String getGetActiveInfoUrl() {
        return getActiveInfoUrl;
    }

    public void setGetActiveInfoUrl(String getActiveInfoUrl) {
        this.getActiveInfoUrl = getActiveInfoUrl;
    }

    public String getGetTransitListUrl() {
        return getTransitListUrl;
    }

    public void setGetTransitListUrl(String getTransitListUrl) {
        this.getTransitListUrl = getTransitListUrl;
    }

    public String getTestUrl() {
        return testUrl;
    }

    public void setTestUrl(String testUrl) {
        this.testUrl = testUrl;
    }

    public boolean isEnclosure() {
        return enclosure;
    }

    public void setEnclosure(boolean enclosure) {
        this.enclosure = enclosure;
    }
}
